package com.ytlz.dmcs.model.system.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ytlz.dmcs.model.system.entity.SysField;
import com.ytlz.dmcs.model.system.entity.SysObject;
import com.ytlz.dmcs.model.system.service.SysObjectService;

@RestController
@RequestMapping("/admin/object")
public class ObjectController {
	
	@Autowired
	private SysObjectService objectService;
	
	@PostMapping("save")
	public Map<String,Object> save(HttpServletRequest request) {
		Map<String,Object> result = new HashMap<String,Object>();
		SysObject obj = new SysObject(request.getParameter("form.name"), request.getParameter("form.label"), "custom");
		
		if(objectService.findByName(obj.getName())==null) {			
			objectService.save(obj);
			result.put("code", 1);
			result.put("message", "success");
		}else{
			result.put("code", 0);
			result.put("message", "创建对象已存在");
			
		}
		
		
		return result;
	}
	
	@PostMapping("remove")
	public Map<String,Object> remove(HttpServletRequest request,@RequestParam(value = "id", required = true) String id) {
		Map<String,Object> result = new HashMap<String,Object>();
		
		objectService.remove(id);
		
		return result;
	}
	
	@PostMapping("getObjectList")
	public List<Document> getObjectList(HttpServletRequest request) {
		List<Document> resultList = new ArrayList<Document>();
		for (SysObject sysObject : objectService.findAll()) {
			Document record = new Document();
			record.append("id", sysObject.getId());
			record.append("text", sysObject.getLabel());
			resultList.add(record);
		}		
		return resultList;
	}
	
	@PostMapping("getAttributeList")
	public List<Document> getAttributeList(HttpServletRequest request,@RequestParam(value = "id", required = true) String id,@RequestParam(value = "scope", required = true) String scope) {
		SysObject obj = objectService.get(id);
		List<Document> result = new ArrayList<Document>();		
		for (SysField field : objectService.getFields(obj, scope)) {
			 Document record = new Document();
			 record.append("id", field.getId());
			 record.append("label", field.getLabel());
			 record.append("name", field.getName());
			 record.append("type",field.getDatatype());
			 record.append("scope", field.getScope());
			 result.add(record);
		}
		return result;
	}
	
}
